package com.mindskip.xzs.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mindskip.xzs.constant.CommonRedisKey;
import com.mindskip.xzs.domain.Question;
import com.mindskip.xzs.repository.NewQuestionMapper;
import com.mindskip.xzs.service.NewQuestionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class NewQuestionServiceImpl extends ServiceImpl<NewQuestionMapper, Question> implements NewQuestionService {
    @Resource
    private RedisTemplate<String,List<String>> redisTemplate;

    /**
     * 更新缓存
     */
    @Override
    public void updateCategorysInCache() {
        List<String> categoryList = baseMapper.queryCategoryList(null);
        if (CollectionUtil.isNotEmpty(categoryList)) {
            redisTemplate.opsForValue().set(CommonRedisKey.ALL_QUESTION_CATEGORY_KEY, categoryList, 30, TimeUnit.DAYS);
        }
    }

    @Override
    public List<String> queryCategoryListInCache(String keyword) {
        List<String> categoryList = redisTemplate.opsForValue().get(CommonRedisKey.ALL_QUESTION_CATEGORY_KEY);
        if (StringUtils.isNotBlank(keyword) && categoryList != null) {
            categoryList = categoryList.stream().filter(category -> category.contains(keyword)).collect(Collectors.toList());
        }
        return categoryList;
    }
}
